var express = require('express');
var router = express.Router();
var logger = require('../common/logger').logger.getLogger("user");
var mysql_query = require('../common/mysql');
var httpresult = require('../common/response');
var md5 = require('md5');
var vertoken = require('../common/token');

router.get('/:course_id/info', async function(req, res, next) {
    var [error, data] = await mysql_query("select course_id, name, title, introduce from course where course_id = ?", [req.params.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length === 0) {
        return res.send(httpresult.trans_error("COURSE_NOT_EXIST", "该科目不存在"));
    }
    var result = data[0];
    // var result = {
    //     info: data[0]
    // }
    return res.send(httpresult.success(result));
});
router.post('/list', async function(req, res, next) {
    let sql = "select * from course where  1 ";
    let where_params = [];
    if (req.body.condition.hasOwnProperty("parent_id")) {
        sql += "and parent_id = ?";
        where_params.push(req.body.condition.parent_id);
    }

    var [error, data] = await mysql_query(sql, where_params);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    data = data.sort((a, b) => {
        return a.order_number - b.order_number;
    });
    return res.send(httpresult.success(data));
});

router.post('/treelist', async function(req, res, next) {
    let sql = "select * from course";
    let [error, data] = await mysql_query(sql, []);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }

    // 先找出所有的父级章节
    let parent_obj = {}
    for(let index in data) {
        if (data[index].parent_id === 0) {
            parent_obj[data[index].course_id] = data[index];
            parent_obj[data[index].course_id].children = [];
        }
    }

    // 再归类子级章节
    for(let index in data) {
        if (data[index].parent_id === 0) {
            continue;
        }
        parent_obj[data[index].parent_id].children.push(data[index]);
    }

    let parent_arr = []
    for (let index in parent_obj) {
        parent_obj[index].children = parent_obj[index].children.sort((a, b) => {
            return a.order_number - b.order_number;
        })
        parent_arr.push(parent_obj[index]);
    }

    parent_arr = parent_arr.sort((a, b) => {
        return a.order_number - b.order_number;
    })
    return res.send(httpresult.success(parent_arr));
});

router.post('/add', async function(req, res, next) {
    let new_order_number = req.body.order_number;
    if (req.body.order_number === "") {
        var [error, data] = await mysql_query(
            "select count(*) from course where parent_id = ?",
            [req.body.parent_id]);
        if (error) {
            logger.warn(error);
            return res.send(httpresult.sys_error(error));
        }
        new_order_number = data[0]['count(*)'] + 1;
    }
    else {
        var [error, data] = await mysql_query(
            "update course set order_number = order_number + 1 where parent_id = ? and order_number >= ? ",
            [req.body.parent_id, req.body.order_number])
        if (error) {
            logger.warn(error);
            return res.send(httpresult.sys_error(error));
        }
    }
    req.body.introduce = req.body.introduce || "";
    var [error, data] = await mysql_query(
        "insert into course (name, title, introduce, icon, order_number, parent_id) value (?, ?, ?, ?, ?, ?)",
        [req.body.name, req.body.title, req.body.introduce,
            req.body.parent_id === 0? "Menu": "Briefcase", new_order_number, req.body.parent_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }

    var [error, data] = await mysql_query(
        "insert into user_course (user_id, course_id) value (?, ?)",
        [req.user_id, data.insertId]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/update', async function(req, res, next) {
    var [error, data] = await mysql_query("update course set name = ?, title = ?, introduce = ? where course_id = ?",
        [req.body.name, req.body.title, req.body.introduce, req.body.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/delete', async function(req, res, next) {
    var [error, data] = await mysql_query("select parent_id from course where course_id = ?", [req.body.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length === 0) {
        return res.send(httpresult.trans_error("COURSE_NOT_EXIST", "该章节不存在"));
    }
    var parent_id = data[0].parent_id;

    var [error, data] = await mysql_query("delete from course where course_id = ?", [req.body.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    [error, data] = await mysql_query(
        "update course set order_number = order_number - 1 where parent_id = ? and order_number > ? ",
        [parent_id, req.body.order_number]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/sort', async function(req, res, next) {
    var sql = "update course set order_number = case course_id ";
    var where_params = [];
    var in_ids = [];
    for (let course_id in req.body.data) {
        sql += " when ? then ? "
        where_params.push(Number(course_id));
        where_params.push(req.body.data[course_id]);
        in_ids.push(Number(course_id));
    }
    sql += " end where course_id in (?)";
    where_params.push(in_ids);
    var [error, data] = await mysql_query(sql, where_params);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.get('/:course_id/chapter/menus', async function(req, res, next) {
    var [error, data] = await mysql_query("select * from chapter where course_id = ?", [req.params.course_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    for (var index in data) {
        data[index]["id"] = data[index].chapter_id;
    }

    // 先找出所有的父级章节
    let parent_obj = {}
    for(let index in data) {
        if (data[index].parent_id === 0) {
            parent_obj[data[index].chapter_id] = data[index];
            parent_obj[data[index].chapter_id].children = [];
        }
    }

    // 再归类子级章节
    for(let index in data) {
        if (data[index].parent_id === 0) {
            continue;
        }
        parent_obj[data[index].parent_id].children.push(data[index]);
    }

    let parent_arr = []
    for (let index in parent_obj) {
        parent_obj[index].children = parent_obj[index].children.sort((a, b) => {
            return a.order_number - b.order_number;
        })
        parent_arr.push(parent_obj[index]);
    }

    parent_arr = parent_arr.sort((a, b) => {
        return a.order_number - b.order_number;
    });
    return res.send(httpresult.success(parent_arr));
    // return res.send({
    //     code: 200,
    //     msg: "",
    //     data: parent_arr
    // })
});

module.exports = router;
